#include "UIConfigWidget.h"
#include <QApplication>
#include <QColorDialog>
#include <QTextCodec>
#include <QSettings>
#include <QKeyEvent>
#include <QFile>
#include <QDir>

namespace TWCore
{
	UIConfigWidget::UIConfigWidget() :
		IConfigWidget()
	{
		ui.setupUi(this);

		QString basePath = qApp->applicationDirPath() + "/theme/";
		QStringList folders = QDir(basePath).entryList(QDir::AllDirs|QDir::NoDotAndDotDot);
		foreach(QString folder,folders)
		{
			themeList.append(folder);
		}
		themeListModel.setStringList(themeList);
		ui.themeCB->setModel(&themeListModel);

		QSettings setting(qApp->applicationDirPath() + "/setting.ini",QSettings::IniFormat);
		setting.beginGroup("Main");
		QString theme = setting.value("Theme","default").toString();
		ui.themeCB->setCurrentIndex(themeList.indexOf(theme));
		ui.groupLengthSB->setValue(setting.value("GroupLength",1).toInt());
		ui.verticalCB->setChecked(setting.value("RepeatBgY",false).toBool());
		ui.horizontalCB->setChecked(setting.value("RepeatBgX",false).toBool());

		setColorButton(setting.value("LinkColor",0xFF0000).toUInt());
		connect(ui.colorButton,SIGNAL(clicked()),this,SLOT(chooseColor()));
		ui.colorButton->setIconSize(QSize(60,22));
		setting.endGroup();

		ui.fontCB->setMaxVisibleItems(20);
		QSettings fsetting(qApp->applicationDirPath() + "/otherSetting.ini",QSettings::IniFormat);
#ifdef Q_OS_WIN32
		QTextCodec* codec = QTextCodec::codecForLocale();
#else
		QTextCodec* codec = QTextCodec::codecForName( "GBK" );
#endif
		fsetting.setIniCodec(codec);
		QString fontName = fsetting.value("Font","").toString();
		ui.fontCB->setCurrentFont(QFont(fontName));
		ui.fontsizeCB->setValue(fsetting.value("FontSize",9).toInt());
	}

	void UIConfigWidget::saveSetting()
	{
		QSettings setting(qApp->applicationDirPath() + "/setting.ini",QSettings::IniFormat);
		setting.beginGroup("Main");
		setting.setValue("Theme",ui.themeCB->currentText());
		setting.setValue("GroupLength",ui.groupLengthSB->value());
		setting.setValue("RepeatBgY",ui.verticalCB->isChecked());
		setting.setValue("RepeatBgX",ui.horizontalCB->isChecked());
		setting.setValue("LinkColor",linkColor);
		setting.endGroup();
		QSettings fsetting(qApp->applicationDirPath() + "/otherSetting.ini",QSettings::IniFormat);
#ifdef Q_OS_WIN32
		QTextCodec* codec = QTextCodec::codecForLocale();
#else
		QTextCodec* codec = QTextCodec::codecForName( "GBK" );
#endif
		fsetting.setIniCodec(codec);
		fsetting.setValue("Font",ui.fontCB->currentFont().family());
		fsetting.setValue("FontSize",ui.fontsizeCB->value());
	}

	void UIConfigWidget::setColorButton(QRgb color)
	{
		linkColor = color;
		QPixmap pixmap(60,22);
		pixmap.fill(QColor(color));
		ui.colorButton->setIcon(pixmap);
	}

	void UIConfigWidget::chooseColor()
	{
		QColor color = QColorDialog::getColor(QColor(linkColor));
		if(color.isValid())
			setColorButton(color.rgb());
	}
}

